package com.vdong.common.oauth.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.CodeManagementAPI;
import com.github.sd4324530.fastweixin.api.CodeTemplateAPI;
import com.github.sd4324530.fastweixin.api.QrcodeAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.config.AuthorizerApiConfig;
import com.github.sd4324530.fastweixin.api.config.ComponentApiConfig;
import com.github.sd4324530.fastweixin.api.entity.AppCategory;
import com.github.sd4324530.fastweixin.api.entity.AuditItem;
import com.github.sd4324530.fastweixin.api.entity.CodeTemplate;
import com.github.sd4324530.fastweixin.api.request.AuditItemRequest;
import com.github.sd4324530.fastweixin.api.response.*;
import com.github.sd4324530.fastweixin.util.SignUtil;
import com.github.sd4324530.fastweixin.util.StrUtil;
import com.google.common.collect.Lists;
import com.vdong.common.oauth.common.enums.AuthorizeTypeEnum;
import com.vdong.common.oauth.common.exception.WebBizException;
import com.vdong.common.oauth.common.pojo.CodeTemplateVO;
import com.vdong.common.oauth.common.pojo.WechatCodeAuditRequest;
import com.vdong.common.oauth.common.pojo.WechatCodeCommitRequest;
import com.vdong.common.oauth.common.pojo.WechatJsConfig;
import com.vdong.common.oauth.common.util.AbstractOpenPlatformSupport;
import com.vdong.common.oauth.entity.mo.*;
import com.vdong.common.oauth.repository.dao.WechatOnlineVersionMapper;
import com.vdong.common.oauth.repository.dao.WechatPublishSettingsMapper;
import com.vdong.common.oauth.service.WechatAuthorizerInfoService;
import com.vdong.common.oauth.service.WechatConfigService;
import com.vdong.common.oauth.service.WechatService;

import com.vdongchina.boot.wechat.util.HttpClient;
import com.vdongchina.boot.wechat.util.WechatUrls;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: kpay-basics-srv
 * @description:
 * @author: Mr.Zhang
 * @create: 2018-06-20 14:43
 **/
@Service
@SuppressWarnings({"rawtypes", "unchecked"})
public class WechatServiceImpl extends AbstractOpenPlatformSupport implements WechatService {
    private static final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);

    private static final String API_GET_SESSION = "https://api.weixin.qq.com/sns/component/jscode2session?"
            + "appid=${appId}&js_code=${code}&grant_type=authorization_code&"
            + "component_appid=${componentAppId}&component_access_token=${componentAccessToken}";
    private static final String API_GET_SESSION2 = "https://api.weixin.qq.com/sns/jscode2session?"
            + "appid=${appId}&js_code=${code}&grant_type=authorization_code&"
            + "secret=${secret}";

    private OkHttpClient client;

    @Autowired
    private OauthDynamicPropertyService oauthDynamicPropertyService;

    public WechatServiceImpl() {
        client = new OkHttpClient.Builder().build();
    }

    //private String token =  oauthDynamicPropertyService.getToken();

    //private String appid = oauthDynamicPropertyService.getAppid();

    //private String secret = oauthDynamicPropertyService.getSecret();

    //private String key = oauthDynamicPropertyService.getKey() ;

    //private String backend_domain =  oauthDynamicPropertyService.getBackendDomain();

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private WechatConfigService wechatConfigService;

    @Resource
    private WechatAuthorizerInfoService wechatAuthorizerInfoService;


//    @Autowired
//    private BucketService bucketService;
//
//    @Autowired
//    private StoreInfoMapper storeInfoMapper;

    @Resource
    private WechatPublishSettingsMapper wechatPublishSettingsMapper;

    @Resource
    private WechatOnlineVersionMapper wechatOnlineVersionMapper;


    @Override
    protected RedisTemplate getRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(redisTemplate.getConnectionFactory());
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        template.setHashKeySerializer(jdkSerializationRedisSerializer);
        template.setValueSerializer(jdkSerializationRedisSerializer);
        return template;
    }

    @Override
    protected String getToken() {
        return oauthDynamicPropertyService.getToken();
    }

    @Override
    protected String getAppId() {
        return oauthDynamicPropertyService.getAppid();
    }

    @Override
    protected String getAESKey() {
        return oauthDynamicPropertyService.getKey();
    }

    @Override
    protected String getSecret() {
        return oauthDynamicPropertyService.getSecret();
    }

    @Override
    public String getAuthUrlNew(Long storeId, Integer authorizeType) {
        String preAuthCode = super.getPreAuthCode();
        if (StringUtils.isEmpty(preAuthCode)) {
            throw new WebBizException("获取第三方平台预授权码失败");
        }
        return WechatUrls.getComponentloginpage(
                getAppId(),
                preAuthCode,
                String.format("%s/wechat/saveAuthInfo/%s/%s", "http://" + oauthDynamicPropertyService.getBackendDomain(), storeId + "", authorizeType + ""));
    }

    @Override
    public String jscode2session(String appId, String code) {
        String url = API_GET_SESSION
                .replace("${appId}", appId)
                .replace("${code}", code)
                .replace("${componentAppId}", getAppId())
                .replace("${componentAccessToken}", super.getComponentApiConfig().getAccessToken());
        JSONObject userInfo = HttpClient.getJSON(url);
        return userInfo.getString("session_key");
    }

    @Override
    public String jscode2session(String appId, String secret, String code) {
        String url = API_GET_SESSION2
                .replace("${appId}", appId)
                .replace("${code}", code)
                .replace("${secret}", secret);
        JSONObject userInfo = HttpClient.getJSON(url);
        return userInfo.getString("session_key");
    }

    private List<CodeTemplateVO> parse2VO(List<CodeTemplate> codeTemplateList) {
        if (codeTemplateList == null) {
            return null;
        }
        List<CodeTemplateVO> result = Lists.newArrayList();
        codeTemplateList.forEach(codeTemplate -> {
            CodeTemplateVO vo = CodeTemplateVO.builder()
                    .templateId(codeTemplate.getTemplateId())
                    .userDesc(codeTemplate.getUserDesc())
                    .userVersion(codeTemplate.getUserVersion())
                    .createTime(new Date(codeTemplate.getCreateTime() * 1000))
                    .build();
            result.add(vo);
        });
        return result;
    }

    /*@Override
    public Boolean checkSignature(String timestamp, String nonce, String signature) {
        return SignUtil.checkSignature(getToken(), signature, timestamp, nonce);
    }*/

    @Override
    public String getAuthorizerAccessToken(String wxAppid) {
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByAppid(wxAppid);
        if (authorizerInfo == null) {
            throw new WebBizException("未查询到授权绑定信息");
        }
        AuthorizerApiConfig config = this.getAuthorizerApiConfig(wxAppid, authorizerInfo.getRefreshToken());
        return config.getAccessToken();
    }

    @Override
    public WechatJsConfig getWechatJsConfig(String appId, String secret, String url) {
        if (StrUtil.hasBlank(appId, secret, url)) {
            return null;
        }
        ApiConfig config = super.getApiConfig(appId, secret);
        String noncestr = RandomStringUtils.randomAlphanumeric(16);
        String timestamp = System.currentTimeMillis() / 1000 + "";
        String signature = SignUtil.genSignature(config.getJsApiTicket(), noncestr, timestamp, url);
        return WechatJsConfig.builder()
                .appId(appId)
                .nonceStr(noncestr)
                .timestamp(timestamp)
                .signature(signature)
                .build();
    }

    @Override
    public List<CodeTemplateVO> getCodeTemplateList() {
        ComponentApiConfig config = super.getComponentApiConfig();
        if (config == null) {
            throw new WebBizException("获取微信平台授权码失败");
        }
        CodeTemplateAPI api = new CodeTemplateAPI(config);
        GetAllCodeTemplateResponse response = api.getTemplateList();
        List<CodeTemplate> codeTemplateList = response.getTemplateList();
        return parse2VO(codeTemplateList);
    }

    @Override
    public Boolean commitCode(WechatCodeCommitRequest commitRequest, String creator) {
//        if (commitRequest == null) {
//            throw new WebBizException("小程序代码提交失败,参数异常");
//        }
//        StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(commitRequest.getStoreId());
//        if (storeInfo == null) {
//            throw new WebBizException("未查询到店铺信息，无法提交代码");
//        }
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeInfo.getId(), AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(commitRequest.getStoreId(), AuthorizeTypeEnum.Mini);
//        //获取api
//        CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
//
//        CodeCommitRequest request = parseRequest(commitRequest, authorizerInfo.getAppid(), storeInfo);
//        BaseResponse response = api.commit(request);
//        Boolean isOk = api.isSuccess(response.getErrcode());
//        logger.info("小程序提交 结果 response:{}", response.toJsonString());
//        if (!isOk) {
//            throw new WebBizException("小程序代码提交失败:" + response.getErrmsg());
//        }
//        //判断是否有历史记录
//        WechatPublishSettings settings = wechatPublishSettingsMapper.selectOne(WechatPublishSettings.builder()
//                .isDel(false)
//                .appId(authorizerInfo.getAppid())
//                .storeId(commitRequest.getStoreId()).build());
//        if (settings == null) {
//            settings = WechatPublishSettings.builder()
//                    .appId(authorizerInfo.getAppid())
//                    .myTemplateId(commitRequest.getMyAppTemplateId())
//                    .storeId(commitRequest.getStoreId())
//                    .appName(authorizerInfo.getNickName())
//                    .version(commitRequest.getUserVersion())
//                    .notes(commitRequest.getUserDesc())
//                    .uploadTime(new Date())
//                    .uploadStatus(Boolean.TRUE)
//                    .createDate(new Date())
//                    .createUser(creator)
//                    .build();
//            wechatPublishSettingsMapper.insert(settings);
//        } else {
//            settings.setMyTemplateId(commitRequest.getMyAppTemplateId());
//            settings.setAppName(authorizerInfo.getNickName());
//            settings.setVersion(commitRequest.getUserVersion());
//            settings.setNotes(commitRequest.getUserDesc());
//            settings.setUploadTime(new Date());
//            settings.setModifyDate(new Date());
//            settings.setModifyUser(creator);
//            settings.setUploadStatus(Boolean.TRUE);
//            wechatPublishSettingsMapper.updateByPrimaryKey(settings);
//        }
        return Boolean.TRUE;
    }

//    private CodeCommitRequest parseRequest(WechatCodeCommitRequest commitRequest, String appId, StoreInfo storeInfo) {
//        Long myTemplateId = commitRequest.getMyAppTemplateId();
//        AppTemplate appTemplate = myAppTemplateService.getCodeTemplate(myTemplateId);
//        if (appTemplate == null) {
//            throw new WebBizException("没有获取到代码模板");
//        }
//        CodeCommitRequest request = new CodeCommitRequest();
//        request.setTemplateId(NumberUtils.toInt(appTemplate.getIdentify()));
//        request.setExtJson(getExtJson(storeInfo, appId, appTemplate, commitRequest));
//        request.setUserVersion(commitRequest.getUserVersion());
//        request.setUserDesc(commitRequest.getUserDesc());
//        return request;
//    }

//    private String getExtJson(StoreInfo storeInfo, String appid, AppTemplate appTemplate, WechatCodeCommitRequest commitRequest) {
//        AppExtInfo appExtInfo = new AppExtInfo();
//        appExtInfo.setExtAppid(appid);
//        //appExtInfo.setPages(new String[]{"pages/index/index"});
//
//        appExtInfo.addExt("app_id", appid);
//        appExtInfo.addExt("store_id", storeInfo.getId());
//        appExtInfo.addExt("store_name", storeInfo.getName());
//        appExtInfo.addExt("pay_ctrl", storeInfo.getPayCtrl());//针对小程序，虚拟支付开关
//
//        // 版本信息
//        appExtInfo.addExt("temp_id", appTemplate.getId());////当前模板的id
//        appExtInfo.addExt("temp_name", appTemplate.getName());//当前模板的名称
//        appExtInfo.addExt("temp_version", appTemplate.getVersion());//当前模板的版本号
//        appExtInfo.addExt("user_version", commitRequest.getUserVersion());//店铺自定义版本号
//
//
//        return appExtInfo.toJsonString();
//    }

    @Override
    public String genAppQrcode(Long storeId) {
//        StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
//        if (storeInfo == null || StringUtils.isBlank(storeInfo.getBucketName())) {
//            throw new WebBizException("店铺存储空间不存在,无法获取二维码");
//        }
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
//        String key = String.format("AppQrcode:StoreId_%s:AppId_%s:", storeId + "", authorizerInfo.getAppid());
//        String qrcodeUrlKey = (String) redisTemplate.opsForValue().get(key);
//        if (qrcodeUrlKey == null) {
//            CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
//            byte[] file = api.getQrcode("");//不需要设置默认页
//            if (file == null || file.length <= 1) {
//                throw new WebBizException("获取二维码失败");
//            }
//            String toKey = String.format("resource/image/jpeg/app_qr_code/storeId_%s_appId_%s.jpg", storeId, authorizerInfo.getAppid());
//            qrcodeUrlKey = bucketService.saveAppQrCode(storeInfo.getBucketName(), toKey, file);
//            //redisTemplate.opsForValue().set(key, qrcodeUrlKey, 7, TimeUnit.DAYS);//体验二维码不会变更
//            redisTemplate.opsForValue().set(key, qrcodeUrlKey);
//        }
//        return storeInfo.getBucketDomain() + "/" + qrcodeUrlKey;
        return null;
    }

    @Override
    public String genGroupQrcode(Long storeId, Long groupId, Long courseId, Integer width) {
//        StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
//        if (storeInfo == null || StringUtils.isBlank(storeInfo.getBucketName())) {
//            throw new WebBizException("店铺存储空间不存在,无法获取二维码");
//        }
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
//        String key = String.format("CourseQrcode:StoreId_%s:GroupId_%s:", storeId + "", groupId + "");
//        String qrcodeUrlKey = (String) redisTemplate.opsForValue().get(key);
//        if (qrcodeUrlKey == null) {
//            QrcodeAPI api = getQrcodeAPI(authorizerInfo);
//            String scene = "" + groupId + "," + courseId;
//            byte[] file = api.createQrcode(scene, "pages/gropShareDeails/gropShareDeails", width);
//            if (file == null || file.length <= 1) {
//                throw new WebBizException("获取二维码失败");
//            }
//            String toKey = String.format("resource/image/jpeg/course_qr_code/storeId_%s_appId_%s_groupId_%s_r_%s.jpg", storeId, authorizerInfo.getAppid(), groupId, RandomStringUtils.randomNumeric(6));
//            qrcodeUrlKey = bucketService.saveAppQrCode(storeInfo.getBucketName(), toKey, file);
//            redisTemplate.opsForValue().set(key, qrcodeUrlKey, 7, TimeUnit.DAYS);
//            //redisTemplate.opsForValue().set(key, qrcodeUrlKey);
//        }
//        return "http://" + storeInfo.getBucketDomain() + "/" + qrcodeUrlKey;
        return null;
    }

    @Override
    public String genH5GroupQrcode(Long storeId, Long groupId, Long courseId, Integer width) {
//        StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
//        if (storeInfo == null || StringUtils.isBlank(storeInfo.getBucketName())) {
//            throw new WebBizException("店铺存储空间不存在,无法获取二维码");
//        }
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Open);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Open);
//        String key = String.format("CourseQrcode:StoreId_%s:GroupId_%s:", storeId + "", groupId + "");
//        String qrcodeUrlKey = (String) redisTemplate.opsForValue().get(key);
//        if (qrcodeUrlKey == null) {
//            QrcodeAPI api = getQrcodeAPI(authorizerInfo);
//            String scene = "" + groupId + "," + courseId;
//            byte[] file = api.createQrcode(scene, "pages/gropShareDeails/gropShareDeails", width);
//            if (file == null || file.length <= 1) {
//                throw new WebBizException("获取二维码失败");
//            }
//            String toKey = String.format("resource/image/jpeg/course_qr_code/storeId_%s_appId_%s_groupId_%s_r_%s.jpg", storeId, authorizerInfo.getAppid(), groupId, RandomStringUtils.randomNumeric(6));
//            qrcodeUrlKey = bucketService.saveAppQrCode(storeInfo.getBucketName(), toKey, file);
//            redisTemplate.opsForValue().set(key, qrcodeUrlKey, 7, TimeUnit.DAYS);
//            //redisTemplate.opsForValue().set(key, qrcodeUrlKey);
//        }
//        return "http://" + storeInfo.getBucketDomain() + "/" + qrcodeUrlKey;
        return null;
    }

    @Override
    public byte[] genCourseQrcodeFile(Long storeId, Long courseId, Integer width) {
        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
        if (!isAuth) {
            throw new WebBizException("未查询出授权信息，请重新授权小程序");
        }
        //获取授权信息
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
        QrcodeAPI api = getQrcodeAPI(authorizerInfo);
        String scene = "" + courseId;
        return api.createQrcode(scene, "pages/courseDetailTwo/courseDetailTwo", width);
    }

    @Override
    public byte[] genAppQrcodeFile(Long storeId) {
        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
        if (!isAuth) {
            throw new WebBizException("未查询出授权信息，请重新授权小程序");
        }
        //获取授权信息
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
        String key = String.format("app_qrcode_file:storeid_%s:appid_%s:", storeId + "", authorizerInfo.getAppid());
        byte[] qrcodeFile = (byte[]) redisTemplate.opsForValue().get(key);
        if (qrcodeFile == null) {
            CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
            //不需要设置默认页
            qrcodeFile = api.getQrcode("");
            if (qrcodeFile == null || qrcodeFile.length <= 1) {
                throw new WebBizException("获取二维码失败");
            }
            //体验二维码不会变更
            redisTemplate.opsForValue().set(key, qrcodeFile, 1, TimeUnit.DAYS);
        }
        return qrcodeFile;
    }

    @Override
    public List<AppCategory> getAppCategory(Long storeId) {
        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
        if (!isAuth) {
            throw new WebBizException("未查询出授权信息，请重新授权小程序");
        }
        //获取授权信息
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
        CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
        GetAllAppCategoryResponse response = api.getCategory();
        return response.getCategoryList();
    }

    @Override
    public List<String> getAppPages(Long storeId) {
        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
        if (!isAuth) {
            throw new WebBizException("未查询出授权信息，请重新授权小程序");
        }
        //获取授权信息
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
        CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
        GetPageConfigResponse response = api.getPage();
        return response.getPageList();
    }

    @Override
    public String submitAppAudit(WechatCodeAuditRequest request, Long publishId, String creator) {
//        if (request == null) {
//            throw new WebBizException("小程序代码提交审核失败,参数异常[缺少配置项]");
//        }
//        if (request.getStoreId() == null) {
//            throw new WebBizException("小程序代码提交审核失败,参数异常[缺少店铺id]");
//        }
//        WechatPublishSettings settings = wechatPublishSettingsMapper.selectByPrimaryKey(publishId);
//        if (settings == null) {
//            throw new WebBizException("小程序未提交开发版本");
//        }
//
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(request.getStoreId(), AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(request.getStoreId(), AuthorizeTypeEnum.Mini);
//
//        WechatAuditVersion auditVersion = wechatAuditVersionMapper.selectOne(WechatAuditVersion.builder()
//                .storeId(request.getStoreId())
//                .appId(authorizerInfo.getAppid())
//                .isDel(Boolean.FALSE).build());
//
//        if (auditVersion != null && auditVersion.getAuditStatus() == AuditStatusConstant.InReview.getValue()) {
//            throw new WebBizException("已有审核中的版本，请勿重复提交");
//        }
//
//        CodeManagementAPI api = getCodeManagementAPI(authorizerInfo);
//        AuditItemRequest auditItemRequest = parseRequest(request);
//        SubmitAuditResponse response = api.submitAudit(auditItemRequest);
//        Boolean isOk = api.isSuccess(response.getErrcode());
//        logger.debug("小程序代码提交审核结果:{}", response.toJsonString());
//        if (!isOk) {
//            throw new WebBizException("小程序代码提交审核失败:" + response.getErrmsg());
//        }
//        Date now = new Date();
//
//        //保存审核内容
//        if (auditVersion == null) {
//            WechatAuditVersion wechatAuditVersion = WechatAuditVersion.builder()
//                    .appId(authorizerInfo.getAppid())
//                    .auditId(response.getAuditId())
//                    .myTemplateId(settings.getMyTemplateId())
//                    .storeId(request.getStoreId())
//                    .appName(settings.getAppName())
//                    .auditVersion(settings.getVersion())
//                    .auditStatus(AuditStatusConstant.InReview.getValue())
//                    .auditTime(now)
//                    .isDel(Boolean.FALSE)
//                    .createDate(now)
//                    .createUser(creator).build();
//            wechatAuditVersionMapper.insert(wechatAuditVersion);
//        } else {
//            auditVersion.setAppName(settings.getAppName());
//            auditVersion.setAuditVersion(settings.getVersion());
//            auditVersion.setAuditStatus(AuditStatusConstant.InReview.getValue());
//            auditVersion.setAuditTime(now);
//            auditVersion.setModifyDate(now);
//            auditVersion.setModifyUser(creator);
//            wechatAuditVersionMapper.updateByPrimaryKey(auditVersion);
//        }
//
//        return response.getAuditId();
        return null;
    }

    @Override
    public Boolean updateAuditResult(String appId, Boolean result, String reason) {
//        logger.info("小程序审核结果消息接收，appid:{},result:{},reason:{}", appId, result, reason);
//////        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByAppid(appId);
//////        if (authorizerInfo == null || authorizerInfo.getStoreId() == null) {
//////            return false;
//////        }
//////        WechatAuditVersion wechatAuditVersion = wechatAuditVersionMapper.selectOne(WechatAuditVersion.builder()
//////                .storeId(authorizerInfo.getStoreId())
//////                .appId(authorizerInfo.getAppid())
//////                .isDel(Boolean.FALSE).build());
//////        if (wechatAuditVersion == null) {
//////            return false;
//////        }
//////        // 审核状态，0为审核成功，1为审核失败，2为审核中
//////        wechatAuditVersion.setAuditStatus(result ? 0 : 1);
//////        wechatAuditVersion.setAuditReason(reason);
//////        wechatAuditVersion.setModifyDate(new Date());
//////        return wechatAuditVersionMapper.updateByPrimaryKey(wechatAuditVersion) > 0;
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean postedOnline(Long storeId) {
//        WechatAuditVersion wechatAuditVersion = wechatAuditVersionMapper.selectOne(WechatAuditVersion.builder()
//                .storeId(storeId)
//                .auditStatus(AuditStatusConstant.Success.getValue())
//                .isDel(Boolean.FALSE).build());
//        if (wechatAuditVersion == null) {
//            throw new WebBizException("该店铺没有待发布版本");
//        }
//
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
//        AuthorizerApiConfig config = super.getAuthorizerApiConfig(authorizerInfo.getAppid(), authorizerInfo.getRefreshToken());
//        if (config == null) {
//            throw new WebBizException("获取微信小程序授权信息失败");
//        }
//        CodeManagementAPI api = new CodeManagementAPI(config);
//        BaseResponse response = api.release();
//        Boolean isOk = api.isSuccess(response.getErrcode());
//        logger.info("小程序发布结果:{}", response.toJsonString());
//
//        WechatOnlineVersion wechatOnlineVersion = wechatOnlineVersionMapper.selectOne(WechatOnlineVersion.builder()
//                .storeId(storeId)
//                .isDel(Boolean.FALSE).build());
//        if (wechatOnlineVersion == null) {
//            wechatOnlineVersion = new WechatOnlineVersion();
//            wechatOnlineVersion.setStoreId(storeId);
//            wechatOnlineVersion.setMyTemplateId(wechatAuditVersion.getMyTemplateId());
//            wechatOnlineVersion.setAppName(wechatAuditVersion.getAppName());
//            wechatOnlineVersion.setNotes(wechatAuditVersion.getNotes());
//            wechatOnlineVersion.setIsDel(Boolean.FALSE);
//            wechatOnlineVersion.setCreateDate(new Date());
//            wechatOnlineVersion.setReleaseDate(new Date());
//            wechatOnlineVersion.setReleaseStatus(isOk);
//            wechatOnlineVersionMapper.insert(wechatOnlineVersion);
//        } else {
//            wechatOnlineVersion.setReleaseStatus(isOk);
//            wechatOnlineVersion.setReleaseDate(new Date());
//            wechatOnlineVersion.setOnlineVersion(wechatAuditVersion.getAuditVersion());
//            wechatOnlineVersion.setNotes(wechatAuditVersion.getNotes());
//            wechatOnlineVersion.setMyTemplateId(wechatAuditVersion.getMyTemplateId());
//            return wechatOnlineVersionMapper.updateByPrimaryKey(wechatOnlineVersion) > 0;
//        }
//        if (isOk) {
//            storeInfoMapper.updatePayCtrl(storeId);//更新小程序支付控制
//        }
//        return isOk;
        return null;
    }

    private AuditItemRequest parseRequest(WechatCodeAuditRequest request) {
        AuditItemRequest auditItemRequest = new AuditItemRequest();
        AuditItem item = new AuditItem();
        item.setTitle(request.getTitle());
        item.setAddress(request.getAddress());
        item.setTag(request.getTag());
        if (request.getFirstId() != null) {
            item.setFirstId(request.getFirstId());
            item.setFirstClass(request.getFirstClass());
        }
        if (request.getSecondId() != null) {
            item.setSecondId(request.getSecondId());
            item.setSecondClass(request.getSecondClass());
        }
        if (request.getThirdId() != null) {
            item.setThirdId(request.getThirdId());
            item.setThirdClass(request.getThirdClass());
        }
        auditItemRequest.addItem(item);
        return auditItemRequest;
    }

    private CodeManagementAPI getCodeManagementAPI(WechatAuthorizerInfo authorizerInfo) {
        if (authorizerInfo == null) {
            throw new WebBizException("未查询到授权信息");
        }
        AuthorizerApiConfig config = super.getAuthorizerApiConfig(authorizerInfo.getAppid(), authorizerInfo.getRefreshToken());
        if (config == null) {
            throw new WebBizException("获取微信小程序授权信息失败");
        }
        return new CodeManagementAPI(config);
    }

    private QrcodeAPI getQrcodeAPI(WechatAuthorizerInfo authorizerInfo) {
        AuthorizerApiConfig config = super.getAuthorizerApiConfig(authorizerInfo.getAppid(), authorizerInfo.getRefreshToken());
        if (config == null) {
            throw new WebBizException("获取微信小程序授权信息失败");
        }
        return new QrcodeAPI(config);
    }

    @Override
    public String genLecturerBindPhoneQrcode(Long storeId, Long lecturerId, Integer width) {
//        StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
//        if (storeInfo == null || StringUtils.isBlank(storeInfo.getBucketName())) {
//            throw new WebBizException("店铺存储空间不存在,无法获取二维码");
//        }
//        Boolean isAuth = wechatAuthorizerInfoService.isAuth(storeId, AuthorizeTypeEnum.Mini);
//        if (!isAuth) {
//            throw new WebBizException("未查询出授权信息，请重新授权小程序");
//        }
//        //获取授权信息
//        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId, AuthorizeTypeEnum.Mini);
//        String key = String.format("LecturerBindPhoneQrcode:StoreId_%s:LecturerId%s:", storeId + "", lecturerId + "");
//        String qrcodeUrlKey = (String) redisTemplate.opsForValue().get(key);
//        if (qrcodeUrlKey == null) {
//            QrcodeAPI api = getQrcodeAPI(authorizerInfo);
//            String scene = "" + lecturerId;
//            byte[] file = api.createQrcode(scene, "pages/lectureBindPhone/lectureBindPhone", width);
//            if (file == null || file.length <= 1) {
//                throw new WebBizException("获取二维码失败");
//            }
//            String toKey = String.format("resource/image/jpeg/lecturer_bind_phone_qr_code/storeId_%s_appId_%s_lecturerId_%s_r_%s.jpg", storeId, authorizerInfo.getAppid(), lecturerId, RandomStringUtils.randomNumeric(6));
//            qrcodeUrlKey = bucketService.saveAppQrCode(storeInfo.getBucketName(), toKey, file);
//            redisTemplate.opsForValue().set(key, qrcodeUrlKey, 7, TimeUnit.DAYS);
//        }
//        return "http://" + storeInfo.getBucketDomain() + "/" + qrcodeUrlKey;
        return null;
    }

    @Override
    public WechatPublishSettings getLastPublishSettingsInfo(Long storeId) {
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId);
        if (authorizerInfo == null) {
            return null;
        }
        WechatPublishSettings settings = wechatPublishSettingsMapper.selectOne(WechatPublishSettings.builder()
                .isDel(Boolean.FALSE)
                .appId(authorizerInfo.getAppid())
                .storeId(storeId).build());
        return settings;
    }

    @Override
    public WechatOnlineVersion getOnlineVersion(Long storeId) {
        WechatAuthorizerInfo authorizerInfo = wechatAuthorizerInfoService.loadByStoreId(storeId);
        if (authorizerInfo == null) {
            return null;
        }
        WechatOnlineVersion wechatOnlineVersion = wechatOnlineVersionMapper.selectOne(WechatOnlineVersion.builder()
                .storeId(storeId)
                .appId(authorizerInfo.getAppid())
                .isDel(Boolean.FALSE).build());
        return wechatOnlineVersion;
    }

    /**
     * 获取开放平台accessToken
     *
     * @return
     */
    @Override
    public String getComponentAccessToken() {
        return super.getComponentApiConfig().getAccessToken();
    }
}
